<template>
  <el-row :gutter="50">
    <el-form
      class="setDevice-form-advance setDevice-form"
      label-width="130px"
      :model="formData"
      :rules="rules"
      :inline="true"
      ref="advancedForm"
    >
      <el-col :span="12">
        <div class="formItem-contain">
          <el-form-item prop="tempAdj" label="温度校正">
            <el-input type="number" v-model="formData.tempAdj"></el-input>
            <div class="form-num-unit">℃</div>
          </el-form-item>
          <el-button class="btn-search" @click="handleConfirm('tempAdj')">确定</el-button>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="formItem-contain">
          <el-form-item prop="tempSetTop" label="温度上限">
            <el-input type="number" v-model="formData.tempSetTop"></el-input>
            <div class="form-num-unit">℃</div>
          </el-form-item>
          <el-button class="btn-search" @click="handleConfirm('tempSetTop')"
            >确定</el-button
          >
        </div>
      </el-col>
      <el-col :span="12">
        <div class="formItem-contain">
          <el-form-item prop="tempSetBot" label="温度下限">
            <el-input v-model="formData.tempSetBot" type="number"></el-input>
            <div class="form-num-unit">℃</div>
          </el-form-item>
          <el-button class="btn-search" @click="handleConfirm('tempSetBot')"
            >确定</el-button
          >
        </div>
      </el-col>
      <el-col :span="12">
        <div class="formItem-contain">
          <el-form-item prop="tolr" label="温控容差">
            <el-input v-model="formData.tolr" type="number"></el-input>
            <div class="form-num-unit">℃</div>
          </el-form-item>
          <el-button class="btn-search" @click="handleConfirm('tolr')">确定</el-button>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="formItem-contain">
          <el-form-item prop="overheat" label="过热保护温度">
            <el-input v-model="formData.overheat" type="number"></el-input>
            <div class="form-num-unit">℃</div>
          </el-form-item>
          <el-button class="btn-search" @click="handleConfirm('overheat')"
            >确定</el-button
          >
        </div>
      </el-col>
      <el-col :span="12">
        <div class="formItem-contain">
          <el-form-item prop="otolr" label="过热保护容差">
            <el-input v-model="formData.otolr" type="number"></el-input>
            <div class="form-num-unit">℃</div>
          </el-form-item>
          <el-button class="btn-search" @click="handleConfirm('otolr')">确定</el-button>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="formItem-contain">
          <el-form-item label="防冻温度" prop="antifreeze">
            <el-select v-model="formData.antifreeze">
              <el-option
                v-for="item in antifreezeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <div class="form-num-unit">℃</div>
          </el-form-item>
          <el-button class="btn-search" @click="handleConfirm('antifreeze')"
            >确定</el-button
          >
        </div>
      </el-col>
      <el-col :span="12">
        <div class="formItem-contain formItem-contain-long">
          <el-form-item prop="triggerTm" label="加热器保护触发时间" labelWidth="150px">
            <el-input v-model="formData.triggerTm" type="number"></el-input>
            <div class="form-num-unit">小时</div>
          </el-form-item>
          <el-button class="btn-search" @click="handleConfirm('triggerTm')"
            >确定</el-button
          >
        </div>
      </el-col>
      <el-col :span="12">
        <div class="formItem-contain">
          <el-form-item prop="protectTm" label="加热器保护时间">
            <el-input v-model="formData.protectTm" type="number" step="10"></el-input>
            <div class="form-num-unit">分钟</div>
          </el-form-item>
          <el-button class="btn-search" @click="handleConfirm('protectTm')"
            >确定</el-button
          >
        </div>
      </el-col>
      <el-col :span="12">
        <div class="formItem-contain">
          <el-form-item prop="humAdj" label="湿度校准">
            <el-input v-model="formData.humAdj" type="number"></el-input>
            <div class="form-num-unit">%</div>
          </el-form-item>
          <el-button class="btn-search" @click="handleConfirm('humAdj')">确定</el-button>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="formItem-contain">
          <el-form-item prop="workType" label="工作类型">
            <el-select v-model="formData.workType">
              <el-option
                v-for="item in workTypeOptions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-button class="btn-search" @click="handleConfirm('workType')"
            >确定</el-button
          >
        </div>
      </el-col>
    </el-form>
  </el-row>
</template>

<script>
export default {
  data() {
    const createRangeValidator = (min, max, fieldName, options = {}) => {
      return (rule, value, callback) => {
        if (value === "" || value === null || value === undefined) {
          callback(new Error(`请输入${fieldName}`));
        } else {
          const numValue = parseFloat(value);
          if (isNaN(numValue)) {
            callback(new Error("请输入有效数字"));
          } else if (options.multipleOf && numValue % options.multipleOf !== 0) {
            callback(new Error(`请输入${min}-${max}之间${options.multipleOf}的倍数值`));
          } else if (numValue < min || numValue > max) {
            callback(new Error(`输入值必须在${min}到${max}之间`));
          } else {
            callback();
          }
        }
      };
    };

    return {
      antifreezeOptions: [],
      workTypeOptions: [],
      formData: {
        tempAdj: 0, // 温度校正 -9~9,默认0
        tempSetTop: 50, // 温度上线 5-85，默认50
        tempSetBot: 5, // 温度下线 2-50，默认5
        tolr: 2, // 温度容差 1-15，默认2
        overheat: 60, // 过热保护温度 15-85，默认60
        otolr: 5, // 过热保护容差 1-25，默认5
        antifreeze: 0, // 防冻温度 2-15，默认关闭防冻
        triggerTm: 0, // 加热器保护触发时间 0-99，默认0
        protectTm: 0, // 加热器保护时间 10-90，默认60，步数10
        humAdj: 0, // 湿度校准 -30-30，默认0，步数1
        invert: 0, // 继电器反向设置 "同向", "反向"
        powerRem: 0, // 断电记忆 "断电记忆", "上电关机", "上电开机"
        workType: 0, // 温控器工作类型
      },
      rules: {
        tempAdj: [
          { required: true, message: "请输入温度校正值", trigger: "blur" },
          {
            validator: createRangeValidator(-9, 9, "温度校正值"),
            trigger: "blur",
          },
        ],
        tempSetTop: [
          { required: true, message: "请输入温度上线值", trigger: "blur" },
          {
            validator: createRangeValidator(5, 85, "温度上线值"),
            trigger: "blur",
          },
        ],
        tempSetBot: [
          { required: true, message: "请输入温度下线值", trigger: "blur" },
          {
            validator: createRangeValidator(2, 50, "温度下线值"),
            trigger: "blur",
          },
        ],
        tolr: [
          { required: true, message: "请输入温控容差", trigger: "blur" },
          {
            validator: createRangeValidator(1, 15, "温控容差"),
            trigger: "blur",
          },
        ],
        overheat: [
          { required: true, message: "请输入过热保护温度", trigger: "blur" },
          {
            validator: createRangeValidator(15, 85, "过热保护温度"),
            trigger: "blur",
          },
        ],
        otolr: [
          { required: true, message: "请输入过热保护容差", trigger: "blur" },
          {
            validator: createRangeValidator(1, 25, "过热保护容差"),
            trigger: "blur",
          },
        ],
        antifreeze: [
          {
            required: true,
            message: "请输入防冻温度",
            trigger: "blur",
          },
        ],
        triggerTm: [
          {
            required: true,
            message: "请输入加热器保护触发时间",
            trigger: "blur",
          },
          {
            validator: createRangeValidator(0, 99, "加热器保护触发时间"),
            trigger: "blur",
          },
        ],
        protectTm: [
          { required: true, message: "请输入加热器保护时间", trigger: "blur" },
          {
            validator: createRangeValidator(10, 90, "加热器保护时间", {
              multipleOf: 10,
            }),
            trigger: "blur",
          },
        ],
        humAdj: [
          { required: true, message: "请输入湿度校准值", trigger: "blur" },
          {
            validator: createRangeValidator(-30, 30, "温度校准值"),
            trigger: "blur",
          },
        ],
        workType: [
          { required: true, message: "请输入温控器工作类型", trigger: "blur" },
          {
            validator: createRangeValidator(0, 3, "温控器工作类型"),
            trigger: "blur",
          },
        ],
      },
    };
  },
  mounted() {
    this.antifreezeOptions = [
      { value: 0, label: "关闭防冻" },
      ...[...Array(14)].map((_, index) => ({
        value: index + 2,
        label: `${index + 2}`,
      })),
    ];
    this.loadDictData("sys_dn_workType", "workTypeOptions");
  },
  methods: {
    handleConfirm(prop) {
      this.$refs.advancedForm.validateField(prop, (errorMessage) => {
        if (errorMessage) {
          // 校验失败，错误信息已在表单中显示
          console.log(`校验失败: ${errorMessage}`);
        } else {
          // 校验成功，可以执行后续操作
          console.log(`${prop} 校验成功，值为: ${this.formData[prop]}`);
          // 这里可以添加实际的业务逻辑，例如发送请求更新设备参数
          this.$message.success(`${this.getFieldLabel(prop)} 设置成功`);
        }
      });
    },

    getFieldLabel(prop) {
      const labels = {
        tempAdj: "温度校正",
        tempSetTop: "温度上线",
        tempSetBot: "温度下线",
        tolr: "温控容差",
        overheat: "过热保护温度",
        otolr: "过热保护容差",
        antifreeze: "防冻温度",
        triggerTm: "加热器保护触发时间",
        protectTm: "加热器保护时间",
        humAdj: "温度校准",
        workType: "温控器工作类型",
      };
      return labels[prop] || prop;
    },
    loadDictData(dictType, targetProperty) {
      queryDictData({ dictType }).then((res) => {
        if (res.code == 0) {
          this[targetProperty] = [...res.data];
          // 如果是workType选项，设置默认值为第一个选项的值
          if (targetProperty === "workTypeOptions" && res.data.length > 0) {
            this.formData.workType = res.data[0].dictValue;
          }
        }
      });
    },
    async loadDictData(dictType, targetProperty) {
      try {
        // 调用 store 中的字典查询方法，传入字典类型
        const data = await this.$store.dispatch("dict/queryDictData", dictType);
        // 根据接口返回的数据格式进行处理
        this[targetProperty] = [{ dictLabel: "所有", dictValue: "" }, ...data];
        if (targetProperty === "workTypeOptions" && data.length > 0) {
          this.formData.workType = data[0].dictValue;
        }
      } catch (error) {
        this.$message.error("获取数据失败");
      }
    },
  },
};
</script>

<style lang="scss">
.el-dialog__body .el-form.setDevice-form-advance {
  .formItem-contain .el-form-item__content {
    margin-left: 0 !important;
    width: calc(100% - 135px) !important;
  }
  .el-input__inner,
  .el-select {
    width: 100% !important;
  }
}
.el-dialog__body .el-form.setDevice-form-advance {
  .formItem-contain.formItem-contain-long .el-form-item__content {
    width: calc(100% - 150px) !important;
  }
}
</style>
